import React, { useEffect, useState } from "react"
import { connect } from "react-redux"
import instance from "../../utils/instance"
import "./Question.css"
import Liker from "../Liker/Liker"

function Question(props) {
    const [answers, setAnswers] = useState([])
    useEffect(() => {
        let questionId = props.question._id
        instance.get(`/answers/${questionId}`).then(data => {
            let list = data.data.data
            setAnswers(list)
        }).then()
    }, [props.userInfo])

    const showDetail = (e) => {
        let questionId = props.question._id
        window.location.href = `#/question/${questionId}`
    }
    return (
        <div className="question_container">
            <div className="question_name">
                <h3 onClick={(e) => { showDetail(e) }}>{props.question.title}</h3>
            </div>
            <div className="question_example">
                {
                    answers.length > 0 ? (
                        <p>
                            <span>{answers[0].answerer.username}:</span>
                            {answers[0].content}
                        </p>
                    ) : (
                            <p className="notAnswers">暂时没有任何人回答该问题，赶紧去试试!</p>
                        )
                }
            </div>
            <div className="question_other">
                {
                    answers.length > 0 ? (<Liker answer={answers[0]} userId={props.userInfo._id} />) : ""
                }
                <div className="question_btn">
                    <ul>
                        <li>
                            <p><span className="iconfont iconxinxi"></span>{answers.length}人已回答</p>
                        </li>
                        <li>
                            <p><span className="iconfont iconshoucang"></span>收藏</p>
                        </li>
                    </ul>
                </div>
            </div>
        </div>
    )
}

const mspStateToProps = (state) => {
    return {
        userInfo: state.home.userInfo
    }
}

export default connect(mspStateToProps, null)(Question)